<template>
  <div>
    <Menu menuActive="/blog" />
    <layout>
      <template v-slot:main>
        <el-row :gutter="20">
          <el-col :lg="18" style="margin-bottom: 20px;" v-loading="markdownLoading" element-loading-text="正在玩命加载中...">
            <div class="left_main_container height_light_bgcolor">
              <h1 style="margin-top:0">{{ articleOtherInfo.data.title }}</h1>
              <div class="desc_and_info">
                <p class="desc">
                  文章简介：{{ articleOtherInfo.data.description }}
                </p>
                <p class="tag_wrapper">
                  <span>文章标签：</span>
                  <template v-if="articleOtherInfo.data.groups">
                    <el-tag class="info_tag_item cursor_class" type="info"
                      @click="hanleClickTag(articleOtherInfo.datadirectionId, item)"
                      v-for="item in articleOtherInfo.data.groups.split(',')" :key="item">{{ item }}</el-tag>
                  </template>
                </p>
              </div>
              <!-- 富文本markdown回显区 -->
              <div class="main_panel_content_container" v-html="articleMarkdownContent" v-highlight>
              </div>
              <div class="toolbox">
                <div class="left_author_wrap">
                  <el-avatar :src="proxy.$baseImgUrl + articleOtherInfo.data.user?.avatar" class="cursor_class"
                    :size="35" @click="handleClickToUserBlog(articleOtherInfo.data.user?.userId)" />
                  <p class="author_name cursor_class"
                    @click="handleClickToUserBlog(articleOtherInfo.data.user?.userId)">{{
                        articleOtherInfo.data.user?.nickName
                    }}</p>
                  <el-button round type="primary" size="small" :loading="fllowbtnLoading"
                    v-if="articleOtherInfo.data.user?.followType !== 3 && articleOtherInfo.data.user?.followType == 1"
                    @click="handleClickFollow(0, articleOtherInfo.data.user?.userId)">关注</el-button>
                  <el-button round size="small" :loading="fllowbtnLoading"
                    v-if="articleOtherInfo.data.user?.followType !== 3 && articleOtherInfo.data.user?.followType == 0"
                    @click="handleClickFollow(1, articleOtherInfo.data.user?.userId)">已关注</el-button>
                  <el-button round size="small" :loading="fllowbtnLoading"
                    v-if="articleOtherInfo.data.user?.followType !== 3 && articleOtherInfo.data.user?.followType == 2"
                    @click="handleClickFollow(1, articleOtherInfo.data.user?.userId)">互相关注</el-button>
                </div>
                <div class="right_esb_wrap">
                  <div class="thumb_wrap">
                    <el-button type="primary" link :loading="thumbLoading" @click="handleClickLike">
                      👍赞 {{ articleOtherInfo.data.likeNum }}
                    </el-button>
                  </div>
                  <div class="esb_item cursor_class">
                    <el-icon>
                      <ChatDotSquare />
                    </el-icon>
                    <span>{{ articleOtherInfo.data.commentCount }}</span>
                  </div>
                  <div class="esb_item">
                    <el-icon>
                      <View />
                    </el-icon>
                    <span>{{ articleOtherInfo.data.pageViewNum }}</span>
                  </div>
                  <div class="esb_item">
                    <el-icon>
                      <Timer />
                    </el-icon>
                    <span>{{ articleOtherInfo.data.createTime }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="comment_container height_light_bgcolor">
              <h1 class="comment_tit">
                <div class="left_c_info">
                  <h1>评论</h1>
                  <span>{{ commentsData.length || 0 }}条</span>
                </div>
                <el-button type="primary" round @click="dialogVisible = true">写评论</el-button>
              </h1>
              <div class="comment_content" v-for="item in commentsData" :key="item.id">
                <!-- 一级评论 -->
                <div class="first_comment">
                  <div class="top_comment_user_info">
                    <div class="comment_avatar_con">
                      <Avatar :avatar-img-url="item.user?.avatar" :nick-name="item.user?.nickName"
                        :remark="item.user?.remark" :interestValue="item.user?.interestValue"
                        :userId="item.user?.userId" :noteNum="item.user?.noteNum" :likeNum="item.user?.likeNum" :followNum="item.user?.followNum"/>
                    </div>
                    <div class="comment_user_con">
                      <p class="comment_user_name">{{ item.user.nickName }}</p>
                      <p class="comment_time">{{ item.createTime }}</p>
                    </div>
                  </div>
                  <div class="bottom_comment_content">
                    <!-- content -->
                    <div>
                      <div style="line-height:1.4">
                        {{ item.content }}
                      </div>
                      <div style="display: flex;justify-content: space-between;">
                        <el-button type="primary" link style="margin:16px 0 0"
                          @click="controlShowReply(item.user.nickName, item.userId, item.id)">回复</el-button>
                        <div class="thumb_wrap">
                          <el-button type="primary" link :loading="liketBtnLoading && item.id === liketId"
                            @click="commentLiketData(item.id, 1, item.isLike)">
                            👍赞({{ item.likeNum }})
                          </el-button>
                          <el-button type="primary" link :loading="liketBtnLoading && item.id === liketId"
                            @click="commentLiketData(item.id, 0, item.isBelittle)">
                            👎踩({{ item.belittleNum }})
                          </el-button>
                          <el-button type="danger" :icon="Delete" size="small" class="delete"
                            :loading="deleteLoading && delId === item.id" @click="deleteCommentData(item.id)"
                            v-if="proxy.$userInfo && proxy.$userInfo.userId === item.user.userId">
                            删除
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 二级评论 回复-->
                <div class="second_comment" v-for="items in item.children" :key="items.id">
                  <div class="top_comment_user_info">
                    <div class="comment_avatar_con">
                      <Avatar :avatar-img-url="items.user?.avatar" :nick-name="items.user?.nickName" :noteNum="items.user?.noteNum" :likeNum="items.user?.likeNum" :followNum="items.user?.followNum"/>
                    </div>
                    <div class="comment_user_con">
                      <p class="comment_user_name">{{ items.user.nickName }} 回复 @{{ items.replyUser &&
                          items.replyUser.nickName
                      }}</p>
                      <p class="second_comment_content">
                        {{ items.content }}
                      </p>
                    </div>
                  </div>
                  <div class="second_comment_time">
                    <div>
                      {{ items.createTime }}
                      <el-button type="primary" link style="margin-left: 10px;"
                        @click="controlShowReply(items.user.nickName, items.user.userId, items.parentId)">回复</el-button>
                    </div>
                    <div class="thumb_wrap">
                      <el-button type="primary" link :loading="liketBtnLoading && items.id === liketId"
                        @click="commentLiketData(items.id, 1, items.isLike)">
                        👍赞({{ items.likeNum }})
                      </el-button>
                      <el-button type="primary" link :loading="liketBtnLoading && items.id === liketId"
                        @click="commentLiketData(items.id, 0, items.isBelittle)">
                        👎踩({{ items.belittleNum }})
                      </el-button>
                      <el-button type="danger" :icon="Delete" size="small" class="delete"
                        :loading="deleteLoading && delId === items.id" @click="deleteCommentData(items.id)"
                        v-if="proxy.$userInfo && proxy.$userInfo.userId === items.user.userId">
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
                <!-- 回复区域 -->
                <div style="margin-top: 12px;margin-left: 56px;"
                  v-show="showReply && (item.id === controlIds || item.children && item.children[0] && item.children[0].id === controlIds)">
                  <el-input maxlength="600" :placeholder="replyPlaceHolder" show-word-limit type="textarea" :rows="6"
                    v-model="replyText" />
                  <div style="display: flex;margin: 10px 0px;justify-content: flex-end;">
                    <el-button type="primary" @click="reply" :loading="replyBtnLoading">回复</el-button>
                  </div>
                </div>
              </div>
              <!-- 分页区域 -->
            </div>
          </el-col>
          <el-col :lg="6">
            <div class="right_main_container height_light_bgcolor">
              <div class="right_top_hot_article_wrapper">
                <el-card class="box-card" shadow="never" style="border:0">
                  <template #header>
                    <div class="card_header">
                      <span>热门文章</span>
                    </div>
                  </template>
                  <div class="card_content" v-loading="hotBlogListLoading" element-loading-text="正在玩命加载中...">
                    <div class="hot_article_item" v-for="item in hotBlogData" :key="item.id"
                      @click="handleClickToArticleDetail(item.id)">
                      <div class="left_img cursor_class">
                        <img :src="proxy.$baseImgUrl + item.coverPicture" alt="" @error="imgError($event)">
                      </div>
                      <div class="right_title text_decoration cursor_class">{{ item.title }}</div>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </layout>
    <Footer />
    <!-- 评论弹出层 -->
    <el-dialog v-model="dialogVisible" title="发表评论" width="50%" @close="handleClickCloseDialog">
      <div>
        <el-input v-model="writeCommentText" :rows="8" type="textarea" placeholder="请发表评论" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClickCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleClickPublishComment" :loading="publishCommentBtnLoading"
            style="width:300px">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import Menu from '@/components/Menu/index.vue'
import Layout from '@/components/Layout/index.vue'
import Footer from '@/components/Footer/index.vue'
import Avatar from '@/components/Avatar/index.vue'
import {
  Delete,
  Tickets,
  UserFilled,
  RefreshLeft,
  Plus,
  Document,
  User,
  ChatDotSquare,
  View,
  Timer,
  Pointer,
  More,
  Location,
  Link
} from '@element-plus/icons-vue'
import { getArticleDetail, commentLiket, deleteComment } from '@/api/article'
import { useRoute } from 'vue-router';
import { onMounted, ref, getCurrentInstance, reactive, toRef, toRefs } from 'vue'
import { blogLike, publishComment } from '@/api/article'
import { ElMessage } from 'element-plus'
import { handleTree } from '@/utils/index'
import { getBlogList } from "@/api/index";
// 将marked 引入
import { marked } from 'marked';
import router from '@/router'
import { followUser } from '@/api/user'
import { imgError } from '@/utils/imgError'
const { proxy } = getCurrentInstance()
const dialogVisible = ref(false)
// 发表评论
const writeCommentText = ref<string>('')
const markdownLoading = ref<boolean>(false)
const thumbLoading = ref<boolean>(false)
const publishCommentBtnLoading = ref<boolean>(false)
const showReply = ref<boolean>(false)
const replyBtnLoading = ref<boolean>(false)
const replyPlaceHolder = ref<string>("请输入内容")
const liketBtnLoading = ref<boolean>(false)
const liketId = ref<number | null>(null)
const delId = ref<number | null>(null)
const deleteLoading = ref<boolean>(false)
const replyText = ref<string>('')
// 评论data
const commentsData = ref<any>([{ user: {}, children: [] }])
// 被回复者id
const replyId = ref<number | null>(null)
const controlIds = ref<number | null>(null)
const fllowbtnLoading = ref<boolean>(false)
const hotBlogListLoading = ref<boolean>(false)
const hotBlogData = ref<any>([])
const Route = useRoute(); //获取到值
const render = new marked.Renderer()
marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false
});
// 文章id
let articleId = ref('')
// 文章内容
const articleMarkdownContent = ref('')
// 文章其他信息
const articleOtherInfo = reactive<any>({ data: { user: {} } })
articleId.value = Route.params.id as string
const getArticleDetailData = async () => {
  if (articleId.value) {
    try {
      markdownLoading.value = true
      const { data } = await getArticleDetail({ id: articleId.value })
      articleOtherInfo.data = data
      commentsData.value = articleOtherInfo.data.comments
      console.log(commentsData.value);
      // 0是富文本
      // 1是markdown
      if (articleOtherInfo.data.type === 0 || articleOtherInfo.data.type === null) {
        // let oStr = htmlToString(data.content)
        // let htmlStr = replaceImg(oStr)
        // console.log(oStr);

        articleMarkdownContent.value = data.content
      } else {
        let str = marked(data.content);
        // let newStr = replaceImg(str)
        // markdown 解析成html字符串
        articleMarkdownContent.value = str
      }
    } finally {
      markdownLoading.value = false
    }
  } else {
    ElMessage({
      message: '获取文章ID失败',
      type: 'error',
      duration: 5 * 1000
    })
  }
}
// 点赞
const handleClickLike = async () => {
  if (articleId.value) {
    try {
      thumbLoading.value = true
      let value = null
      articleOtherInfo.data.isLike === 0 ? value = 1 : value = 0
      const res: any = await blogLike({
        id: articleId.value,
        value
      })
      if (res) {
        if (value === 1) {
          ElMessage({
            message: '点赞成功',
            type: 'success',
            duration: 5 * 1000
          })
        } else {
          ElMessage({
            message: '取消点赞成功',
            type: 'success',
            duration: 5 * 1000
          })
        }
        getArticleDetailData()
      }
    } finally {
      thumbLoading.value = false
    }
  } else {
    ElMessage({
      message: '获取文章ID失败',
      type: 'error',
      duration: 5 * 1000
    })
  }
}
// 发表评论
const handleClickPublishComment = async () => {
  if (writeCommentText.value.trim() === '' || writeCommentText.value.trim() === null) {
    return ElMessage({
      message: '评论内容不能为空',
      type: 'error',
      duration: 5 * 1000
    })
  }
  if (articleId.value) {
    try {
      publishCommentBtnLoading.value = true
      const res: any = await publishComment({ noteId: articleId.value, parentId: 0, content: writeCommentText.value })
      if (res) {
        ElMessage({
          message: '评论发表成功',
          type: 'success',
          duration: 2 * 1000,
        })
        getArticleDetailData()
      }
      dialogVisible.value = false
      writeCommentText.value = ''
    } finally {
      publishCommentBtnLoading.value = false
    }

  } else {
    ElMessage({
      message: '获取文章ID失败',
      type: 'error',
      duration: 5 * 1000
    })
  }
}
/**
 * 展示评论框
 * @param nickName 
 * @param id
 */
const controlShowReply = (nickName: string, id: number, controlId: number) => {
  showReply.value = true
  replyId.value = id
  controlIds.value = controlId
  replyPlaceHolder.value = "回复：" + nickName
}
/**
 * 评论点赞或踩
 * @param commentId 
 * @param type 
 * @param flag 判断是否点踩了或赞了
 */
const commentLiketData = async (commentId: number, type: number, flag: number) => {
  console.log('flag------------------', flag);
  liketId.value = commentId
  try {
    liketBtnLoading.value = true
    let value = null
    flag === 0 ? value = 1 : value = 0
    console.log('value---------------', value);
    const res: any = await commentLiket({
      commentId,
      type,
      value
    })
    if (res) {
      if (type === 1) {
        if (value === 1) {
          ElMessage({
            message: '点赞成功',
            type: 'success',
            duration: 2 * 1000,
          })
        } else {
          ElMessage({
            message: '取消点赞成功',
            type: 'success',
            duration: 2 * 1000,
          })
        }
      } else {
        if (value === 1) {
          ElMessage({
            message: '点踩成功',
            type: 'success',
            duration: 2 * 1000,
          })
        } else {
          ElMessage({
            message: '取消点踩成功',
            type: 'success',
            duration: 2 * 1000,
          })
        }
      }
      getArticleDetailData()
    }
  } finally {
    liketBtnLoading.value = false
  }
}
/**
 * 评论回复
 */
const reply = async () => {
  if (replyText.value.trim() === '' || replyText.value.trim() === null) {
    return ElMessage({
      message: '回复内容不能为空',
      type: 'error',
      duration: 5 * 1000
    })
  }
  if (articleId.value) {
    try {
      replyBtnLoading.value = true
      const res: any = await publishComment({ noteId: articleId.value, parentId: controlIds.value, replyUserId: replyId.value, content: replyText.value })
      if (res) {
        ElMessage({
          message: '回复成功',
          type: 'success',
          duration: 2 * 1000,
        })
        getArticleDetailData()
      }
      showReply.value = false
      replyText.value = ''
    } finally {
      replyBtnLoading.value = false
    }
  } else {
    ElMessage({
      message: '获取文章ID失败',
      type: 'error',
      duration: 5 * 1000
    })
  }
}
/**
 * 删除评论
 * @param id 评论id
 */
const deleteCommentData = async (id: number) => {
  try {
    delId.value = id
    deleteLoading.value = true
    const res: any = await deleteComment({ id })
    if (res) {
      ElMessage({
        message: '删除评论成功',
        type: 'success',
        duration: 2 * 1000,
      })
      getArticleDetailData()
    }
  } finally {
    deleteLoading.value = false
  }
}
const handleClickCloseDialog = () => {
  writeCommentText.value = ''
  dialogVisible.value = false
}
// 更改图片路径
function replaceImg(content: string) {
  return content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
    // return `<img src = https://hubi.work/${capture}/>`
    // return `<img src = http://114.132.240.29:8080/${capture}/>`
  })
}
// 剔除富文本的标签 换行 空格
function htmlToString(htmlStr: string) {
  return htmlStr.replace(/<\/?.+?\/?>|\r|\n|\s*/g, '')
}
const hanleClickTag = (directionId: number, item: string) => {
  const url = router.resolve({
    path: '/blog',
    query: {
      tagname: encodeURIComponent(item),
      dirId: directionId
    }
  })
  window.open(url.href, '_blank')
}
const handleClickToUserBlog = (userId: number | string) => {
  router.push({
    name: 'user-blog',
    params: {
      id: userId
    }
  })
}
const handleClickFollow = async (status: number, followedUserId: number) => {
  try {
    fllowbtnLoading.value = true
    const res: any = await followUser({
      followedUserId,
      status
    })
    if (res) {
      if (status === 1) {
        ElMessage({
          message: '取关成功',
          type: 'success',
          duration: 2 * 1000
        })
      } else {
        ElMessage({
          message: '关注成功',
          type: 'success',
          duration: 2 * 1000
        })
      }
    }
  } finally {
    fllowbtnLoading.value = false
  }
}
const getBlogListData = async () => {
  try {
    hotBlogListLoading.value = true
    const { rows }: any = await getBlogList({
      isHot: 1
    })
    hotBlogData.value = rows
  } finally {
    hotBlogListLoading.value = false
  }
}
const handleClickToArticleDetail = (id: string) => {
  const url = router.resolve({
    name: 'article-detail',
    params: {
      id
    }
  })
  window.open(url.href, '_blank')
}
onMounted(() => {
  getArticleDetailData()
  getBlogListData()
})
</script>

<style scoped lang="scss">
@import './index.scss';

:deep(*) {
  font-family: Avenir, Helvetica, Arial, sans-serif;
}

:deep(img) {
  max-width: 100%;
}

// :deep(code,
//   kbd,
//   samp) {

// }
</style>
